/**
 * city基础接口
 */
const AV = require("leanengine");
const BaseService = require("./baseService");
class Service extends BaseService {
  constructor() {
    super('City');
  }

  async add(ctx) {
    let {
      isHot,
      name,
      pinyin
    } = ctx.params;
    let result = this.checkAttr(["isHot", "name", "pinyin"], ctx.params);
    if (result) return result;
    try {
      // 检查城市名称是否存在
      result = await this.checkName(name);
      console.log("result", result);
      if (result) return result;
      await this.addInterface(ctx.params);
      return {
        msg: "success",
        code: "666"
      };
    } catch (error) {
      console.log(error);
      return {
        code: error.code,
        msg: error.message
      };
    }
  }

  async edit(ctx) {
    const {
      cityId
    } = ctx.params;
    if (!cityId) {
      return {
        code: 601,
        msg: "缺少cityId"
      };
    }
    try {
      const entry = AV.Object.createWithoutData("City", cityId);
      const params = ctx.params;
      for (let p in params) {
        entry.set(p, params[p]);
      }
      const result = await entry.save();
      return {
        code: "666",
        msg: "success",
        result
      };
    } catch (error) {
      console.log("error", error);
      return {
        code: error.code,
        msg: error.message
      };
    }
  }

  // 找出区域列表里的所有城市id
  async getAreas() {
    return new Promise(async (resolve, reject) => {
      try {
        let query = new AV.Query('Area');
        let result = await query.find();
        // 查出所有城市的id
        let cityIds = result.map(item => {
          return item.get('cityId');
        })
        if (cityIds.length > 0) {
          resolve(cityIds)
        } else {
          resolve([])
        }
      } catch (error) {
        reject(error);
      }
    })
  }

  // 专门给影院模块使用的
  async allCity(ctx) {
    let query = new AV.Query('City');
    try {
      let result = await query.find();
      let cityIds = await this.getAreas();
      let cities = result.map(item => {
        let hasArea = cityIds.includes(item.id);
        return {
          ...item.attributes,
          cityId: item.id,
          hasArea
        }
      })
      return {
        cities,
        code: '666',
        msg: 'success'
      }
    } catch (error) {
      return {
        ...this.errInfo(error)
      }
    }
  }

  async findById(ctx) {
    const {
      cityId
    } = ctx.params;
    if (!cityId) {
      return {
        code: 601,
        msg: "缺少cityId"
      };
    }
    const query = new AV.Query("City");
    try {
      const result = await query.get(cityId);
      let name = result.get("name");
      let pinyin = result.get("pinyin");
      // 转变为布尔类型
      // let isHot = result.get("isHot") === "true";
      let isHot = result.get("isHot");
      return {
        code: "666",
        city: {
          cityId,
          name,
          pinyin,
          isHot
        }
      };
    } catch (error) {
      let {
        code
      } = error;
      if (code == 101) {
        return {
          code: 101,
          msg: "城市不存在"
        };
      } else {
        return {
          ...error
        };
      }
    }
  }

  // 删除城市时,删除其下面的地区
  async delArea(cityId) {
    return new Promise(async (resolve, reject) => {
      try {
        let query = new AV.Query('Area');
        query.equalTo('cityId', cityId);
        let areas = await query.find();
        let result = AV.Object.destroyAll(areas);
        console.log(result);
        resolve(true);
      } catch (error) {
        reject(error);
      }
    })
  }

  /**
   * 删除城市时,连同它下面的地区一块删掉
   * @param {*} ctx 
   */
  async delById(ctx) {
    let result = this.checkAttr(['cityId'], ctx.params);
    if (result) return result;
    let {
      cityId
    } = ctx.params;
    try {
      let res1 = await this.delInterfaceById(cityId);
      let res2 = await this.delArea(cityId);
      return {
        res1,
        res2,
        code: "666",
        msg: "删除成功"
      };
    } catch (error) {
      return {
        code: error.code,
        msg: error.message
      };
    }
  }

  // 根据城市名称搜索城市
  async findCityByName(ctx) {
    const {
      cityName
    } = ctx.params;
    try {
      const query = new AV.Query("City");
      query.equalTo("name", cityName);
      const res = await query.find();
      if (res.length) {
        return {
          code: "666",
          city: {
            cityId: res[0].id,
            ...res[0]._serverData
          }
        };
      }

      return {
        code: "666",
        msg: "城市不存在",
        city: {}
      };
    } catch (error) {
      console.log(error);
      return {
        ...error,
        msg: "城市不存在",
        code: 500
      };
    }
  }

  async getList(ctx) {
    const {
      pageNum = 1, pageSize = 10
    } = ctx.params;

    try {
      const query = new AV.Query("City");
      query.limit(pageSize);
      query.skip(pageNum * pageSize - pageSize);
      // 升序
      // query.ascending('createdAt');
      // 降序
      query.descending("createdAt");
      const total = await query.count();
      // const totalPage = Math.ceil(count / pageSize);
      const result = await query.find();
      let cities = result.map(city => {
        return {
          ...city.attributes,
          cityId: city.id,
          create: city.get("createdAt")
        };
      });
      return {
        code: "666",
        msg: "success",
        pageNum,
        total,
        cities
      };
    } catch (error) {
      console.log(error);
      return {
        code: 500,
        ...error,
        msg: "获取列表失败"
      };
    }
  }
}

const service = new Service();
module.exports = service;